﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

public partial class createGroup : System.Web.UI.Page
{
    //声明私有变量来存储userID方便以后使用
    private string userID;

    /// <summary>
    /// 验证是否登录
    /// 初始化边栏内容
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        //如果是因为回传而执行此函数，将边栏的列表清空，否则会出现重复记录的现象
        if (IsPostBack)
        {
            requestlistUl.InnerHtml = "";
            grouplistUl.InnerHtml = "";
        }

        //验证是否登录
        if (Request.Cookies["userID"] == null)
        {
            Response.Redirect("notLogin.html", true);
            return;
        }
        else
        {
            //获取已登录用户信息
            userID = Request.Cookies["userID"].Value;

            ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["connectionstring"];
            using (SqlConnection dataBaseConnection = new SqlConnection(settings.ConnectionString))
            {
                dataBaseConnection.Open();

                //获取待处理的请求列表
                string queryString = "SELECT username, GroupName, RequestList.GroupID, RequestList.userID " +
                                     "FROM users, GroupInfo, RequestList " +
                                     "WHERE CreatedBy = @CreatedBy AND GroupInfo.GroupID = RequestList.GroupID AND RequestList.userID = users.userID";
                SqlCommand command = new SqlCommand(queryString, dataBaseConnection);
                SqlParameter CreatedByParameter = new SqlParameter("@CreatedBy", userID);
                command.Parameters.Add(CreatedByParameter);
                SqlDataReader reader;
                try
                {
                    reader = command.ExecuteReader();
                }
                catch (Exception exception)
                {
                    Response.Redirect("DBError.aspx?error_msg=" + exception.Message.Replace(' ', '-') + "-AFTER-QUERY-OF-REQUEST", true);
                    return;
                }

                //查看是否有请求需要显示
                if (!reader.HasRows)
                {
                    requestlistUl.InnerHtml = "<p>暂时没有需要您处理的请求</p>";
                }
                else
                {
                    while (reader.Read())
                    {
                        requestlistUl.InnerHtml += "<li>" + reader["username"] + "申请加入您的小组" + reader["GroupName"] + "<br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;<a href=\"processRequest.aspx?userID=" + reader["userID"] + "&groupID=" + reader["GroupID"] + "&accepted=1\"><img src=\"images/accepted.png\"></a>  <a href=\"processRequest.aspx?userID=" + reader["userID"] + "&groupID=" + reader["GroupID"] + "&accepted=0\"><img src=\"images/denied.png\"></a></li>";
                    }
                }
                reader.Close();


                //获取该用户加入的小组列表
                queryString = "SELECT GroupIDs " +
                              "FROM users " +
                              "WHERE userID = @userID";
                command.CommandText = queryString;
                command.Parameters.Clear();
                SqlParameter userIDParameter = new SqlParameter("@userID", userID);
                command.Parameters.Add(userIDParameter);
                try
                {
                    reader = command.ExecuteReader();
                }
                catch (Exception exception)
                {
                    Response.Redirect("DBError.aspx?error_msg=" + exception.Message.Replace(' ', '-'), true);
                    return;
                }

                reader.Read();
                string[] groups = reader["GroupIDs"].ToString().Split('&');
                reader.Close();

                if (groups[0] == string.Empty)      //第0元素即是第一个小组名
                {
                    grouplistUl.InnerHtml = "您还没有加入任何小组";
                }
                else
                {
                    //拆分后的数组不为空，显示小组列表
                    int groupNum = groups.Length;
                    for (int i = 0; i < groupNum; i++)
                    {
                        //通过小组ID查询小组名
                        if (groups[i] != string.Empty)
                        {
                            queryString = "SELECT GroupName " +
                                          "FROM GroupInfo " +
                                          "WHERE GroupID = @GroupID";
                            command.CommandText = queryString;
                            command.Parameters.Clear();
                            SqlParameter GroupIDParameter = new SqlParameter("@GroupID", groups[i]);
                            command.Parameters.Add(GroupIDParameter);
                            try
                            {
                                reader = command.ExecuteReader();
                            }
                            catch (Exception exception)
                            {
                                Response.Redirect("DBError.aspx?error_msg=" + exception.Message.Replace(' ', '-'), true);
                                return;
                            }

                            reader.Read();
                            string groupName = reader["GroupName"].ToString();
                            reader.Close();
                            grouplistUl.InnerHtml += "<li><a href=\"groupIndex.aspx?groupID=" + groups[i] + "&groupName=" + groupName + "\">" + groupName + "</a></li>";
                        }
                    }
                }
                dataBaseConnection.Close();
            }
        }
    }

    /// <summary>
    /// 执行创建小组相关工作：
    /// 检查空值、重复
    /// 创建成功（数据库操作完成）后：
    /// 进入小组主页并设置cookie
    /// 创建动态用的xml文件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void submit_Click(object sender, EventArgs e)
    {
        string groupName_worked = groupName.Text.Trim();

        if (groupName_worked == string.Empty)
        {
            notification.InnerHtml = "请输入小组名称";
            return;
        }
        else
        {
            ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["connectionString"];
            using (SqlConnection dataBaseConnection = new SqlConnection(settings.ConnectionString))
            {
                dataBaseConnection.Open();

                //检查小组是否已经存在
                string queryString = "SELECT GroupID " +
                                     "FROM GroupInfo " +
                                     "WHERE GroupName = @GroupName";
                SqlCommand command = new SqlCommand(queryString, dataBaseConnection);
                SqlParameter GroupNameParameter = new SqlParameter("@GroupName", groupName_worked);
                command.Parameters.Add(GroupNameParameter);
                SqlDataReader reader;
                try
                {
                    reader = command.ExecuteReader();
                }
                catch (Exception exception)
                {
                    notification.InnerHtml = "数据库方面发生了错误，请联系我们来解决 AFTER EXISTING CHECK<br>" + exception.Message;
                    return;
                }

                if (reader.HasRows)
                {
                    notification.InnerHtml = "您想要创建的小组名称已经存在，请换一个名字重试";
                    return;
                }
                else
                {
                    reader.Close();

                    //小组不存在，执行创建

                    //将小组信息加入GroupInfo
                    DateTime createDate = DateTime.Now;

                    queryString = "INSERT INTO GroupInfo(GroupName, CreatedBy, CreateDate) " +
                                  "VALUES(@GroupName, @CreatedBy, @CreateDate)";
                    command.CommandText = queryString;
                    SqlParameter CreatedByParameter = new SqlParameter("@CreatedBy", userID);
                    SqlParameter CreateDateParameter = new SqlParameter("@CreateDate", createDate);
                    command.Parameters.AddRange(new SqlParameter[]{CreateDateParameter, CreatedByParameter});
                    try
                    {
                        command.ExecuteNonQuery();
                    }
                    catch (Exception exception)
                    {
                        notification.InnerHtml = "数据库方面发生了错误，请联系我们来解决 AFTER INSERT<br>" + exception.Message;
                        return;
                    }

                    //查询GroupID，用来设置cookie，以及将小组ID添加到用户信息
                    queryString = "SELECT GroupID " +
                                  "FROM GroupInfo " +
                                  "WHERE GroupName = @GroupName";
                    command.CommandText = queryString;
                    command.Parameters.Clear();
                    command.Parameters.Add(GroupNameParameter);
                    try
                    {
                        reader = command.ExecuteReader();
                    }
                    catch (Exception exception)
                    {
                        notification.InnerHtml = "数据库方面发生了错误，请联系我们来解决 AFTER GET GROUPID<br>" + exception.Message;
                        return;
                    }

                    reader.Read();
                    string groupID = reader["GroupID"].ToString();
                    Response.Cookies.Add(new HttpCookie("groupID", groupID));
                    Response.Cookies.Add(new HttpCookie("groupName", groupName_worked));
                    reader.Close();
                    
                    //将小组ID添加到用户信息

                    //查询已经存在于用户信息中的小组ID
                    queryString = "SELECT GroupIDs " +
                                  "FROM users " +
                                  "WHERE userID = @userID";
                    command.CommandText = queryString;
                    command.Parameters.Clear();
                    SqlParameter userIDParameter = new SqlParameter("@userID", userID);
                    command.Parameters.Add(userIDParameter);
                    try
                    {
                        reader = command.ExecuteReader();
                    }
                    catch (Exception exception)
                    {
                        notification.InnerHtml = "数据库方面发生了错误，请联系我们来解决 AFTER GET GROUPIDs<br>" + exception.Message;
                        return;
                    }

                    reader.Read();
                    string groups = reader["GroupIDs"].ToString();
                    reader.Close();

                    //将刚刚创建的小组加入小组字符串中
                    groups = groups + "&" + groupID;

                    //将新的小组字符串加入数据库
                    queryString = "UPDATE users " +
                                  "SET GroupIDs = @GroupIDs " +
                                  "WHERE userID = @userID";
                    command.CommandText = queryString;
                    SqlParameter GroupIDsParameter = new SqlParameter("@GroupIDs", groups);
                    command.Parameters.Add(GroupIDsParameter);
                    try
                    {
                        command.ExecuteNonQuery();
                    }
                    catch (Exception exception)
                    {
                        notification.InnerHtml = "数据库方面发生了错误，请联系我们来解决 AFTER UPDATE GROUPs<br>" + exception.Message;
                        return;
                    }

                    //将创建者与小组的归属关系加入数据库
                    queryString = "INSERT INTO MembersOfGroups(GroupID, MemberID) " +
                                  "VALUES(@GroupID, @userID)";
                    command.CommandText = queryString;
                    command.Parameters.Remove(GroupIDsParameter);
                    SqlParameter GroupIDParameter = new SqlParameter("@GroupID", groupID);
                    command.Parameters.Add(GroupIDParameter);
                    try
                    {
                        command.ExecuteNonQuery();
                    }
                    catch (Exception exception)
                    {
                        notification.InnerHtml = "数据库方面发生了错误，请联系我们来解决 AFTER INSERT MembersOfGroups<br>" + exception.Message;
                        return;
                    }

                    //创建动态用的XML文件

                    //创建文件并添加声明节点
                    XmlDocument xmlDocument = new XmlDocument();
                    XmlNode xmlNode = xmlDocument.CreateNode(XmlNodeType.XmlDeclaration, "", "");
                    xmlDocument.AppendChild(xmlNode);

                    //创建根节点<Feeds>
                    XmlElement xmlElement = xmlDocument.CreateElement("Feeds");

                    //创建根节点属性groupID
                    XmlAttribute attribute = xmlDocument.CreateAttribute("groupID");
                    attribute.Value = groupID;
                    xmlElement.Attributes.Append(attribute);

                    //创建根节点属性groupName
                    attribute = xmlDocument.CreateAttribute("groupName");
                    attribute.Value = groupName_worked;
                    xmlElement.Attributes.Append(attribute);

                    //创建根节点属性count
                    attribute = xmlDocument.CreateAttribute("count");
                    attribute.Value = "0";
                    xmlElement.Attributes.Append(attribute);

                    //将根节点<Feeds>添加到xml文档中
                    xmlDocument.AppendChild(xmlElement);

                    //将文件存入磁盘
                    try
                    {
                        xmlDocument.Save(Server.MapPath("~/Feeds/" + groupID + "_Feeds.xml"));
                    }
                    catch (Exception exception)
                    {
                        notification.InnerHtml = "XML文件创建失败<br>" + exception.Message;
                        return;
                    }

                    //todo 如果动态和日历需要数据库支持就在这里操作

                    dataBaseConnection.Close();
                    Response.Redirect("groupIndex.aspx?groupID=" + groupID + "&groupName=" + groupName_worked, true);
                }
            }
        }
    }
}